package com.ry.request;

import com.ry.common.utils.RedisUtil;
import com.ry.model.ProductInventory;
import com.ry.service.ProductInventoryService;
import lombok.extern.slf4j.Slf4j;

/**
 * 更新数据库库存的请求
 *
 * 当有库存更新的请求过来时，需要做两个操作：
 *  1、先删除缓存
 *  2、更新数据库
 */
@Slf4j
public class InventoryUpdateDbRequest implements InventoryRequest {

    /**
     * redis缓存工具类
     */
    private RedisUtil redisUtil;

    /**
     * 商品库存service
     */
    private ProductInventoryService productInventoryService;

    /**
     * 商品库存实体
     */
    private ProductInventory productInventory;

    public InventoryUpdateDbRequest(RedisUtil redisUtil, ProductInventoryService productInventoryService, ProductInventory productInventory) {
        this.redisUtil = redisUtil;
        this.productInventoryService = productInventoryService;
        this.productInventory = productInventory;
    }

    @Override
    public void process() {
        log.info("===日志===：数据库更新库存请求开始，商品id={}，库存={}",productInventory.getProductId(),productInventory.getInventoryCnt());

        // 1、先删除缓存
        redisUtil.removeInventoryCache(productInventory.getProductId());

        // 2、再更新数据库
        productInventoryService.updateInventoryById(productInventory);
    }


    @Override
    public Long getProductId() {
        return productInventory.getProductId();
    }

    @Override
    public boolean isForced() {
        return false;
    }
}
